package no10;

/**
 * 此例子用说明内部的使用
 * 用到了迭代器模式
 * 与此也可以参考hashmap中的entry实现的内部类
 */
/**
 * holds a sequence of Objects
 * 
 * @author gao
 * 
 */
class A{
	public static void main(String[] args) {
		//其它类要访问内部类时
		//要使用外部类的引用来创建内部类的引用
		Sequence s = new Sequence(10);
		Sequence.SequenceSelector selector = s.new SequenceSelector();
	}
}

interface Selector {
	boolean end();
	Object current();
	void next();
}

public class Sequence {
	private Object[] items;
	private int next = 0;

	public Sequence(int size) {
		items = new Object[size];
	}

	public void add(Object x) {
		if (next < items.length) {
			items[next++] = x;
		}
	}

	/**
	 * 内部实现迭代模式,好处是此内部类可以直接访问Sequence的所有成员
	 * 
	 * @author gao
	 * 
	 */
	public class SequenceSelector  implements Selector{
		private int i = 0;
		
		private void inner(){
			//在内部类的方法中生成外部类的引用
			Sequence s = Sequence.this;
		}
		
		public boolean end() {
			
			return i == items.length;
		}

		public Object current() {
			return items[i];
		}

		public void next() {
			if (i <= items.length) {
				i++;
			}
		}
	}

	/**
	 * 类似于hashmap中的 Set<Map.Entry<K,V>> entrySet()
	 * 
	 * @return
	 */
	public Selector selector() {
		return new SequenceSelector();
	}

	public static void main(String[] args) {
		Sequence sequence = new Sequence(10);
		for (int i = 0; i < 10; i++)
			sequence.add(Integer.valueOf(i));

		Selector selector = sequence.selector();
		while(!selector.end()){
			System.out.println(selector.current());
			selector.next();
		}
	}
}

